package service

import (
	"fmt"
	"gitee.com/arjunxw/iothub-south-client/util"
	"gorm.io/gorm"
	"time"
)

const (
	Enable  = "Enable"
	Disable = "Disable"
	Delete  = "Delete"
)

type Model struct {
	ID        int64     `gorm:"type:bigint;primarykey"`
	CreatedAt time.Time `gorm:"column:created_time;not null"`
	UpdatedAt time.Time `gorm:"column:updated_time;not null"`
	DataState string    `gorm:"type:varchar(20);not null"`
}

func (model *Model) BeforeCreate(tx *gorm.DB) error {
	id := util.NextSnowFlakeID()
	if id == 0 {
		return fmt.Errorf("failed to generate snowflake ID")
	}
	model.ID = id
	model.DataState = Enable
	return nil
}

type DalInfo struct {
	Model
	DalID           string `gorm:"not null"`
	Secret          string `gorm:"not null"`
	AccessToken     string
	RefreshToken    string
	ExpiresIn       int32
	TokenType       string
	LastRequestTime int64
	Scope           string
}

func (model *DalInfo) TableName() string {
	return "t_client_dal_info"
}

const (
	Pending = "Pending"
	Failure = "Failure"
	Success = "Success"
)

type ReportHistory struct {
	Model
	ReportId     string `gorm:"not null"`
	Content      string `gorm:"not null"`
	Url          string `gorm:"not null"`
	ProductKey   string `gorm:"not null"`
	Sn           string `gorm:"not null"`
	RetryTimes   int32  `gorm:"not null"`
	Status       string `gorm:"not null"`
	LastSendTime *time.Time
	DalInfoId    int64 `gorm:"not null"`
	Reason       string
}

func (rh *ReportHistory) TableName() string {
	return "t_client_report_history"
}

type RetryRecord struct {
	Model
	ReportHistory *ReportHistory `gorm:"ForeignKey:ReportID;AssociationForeignKey:ID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;"`
	ReportID      int64          `gorm:"uniqueIndex:idx_client_retry_record_report_id_next;not null"`
	Prev          *time.Time
	Next          *time.Time `gorm:"uniqueIndex:idx_client_retry_record_report_id_next,sort:asc"`
	RetryTimes    int32      `gorm:"not null"`
}

func (rr *RetryRecord) TableName() string {
	return "t_client_retry_record"
}
